﻿using AnalyStock.DataManage;
using System.ComponentModel;
using System.Windows.Navigation;
using System.Windows.Threading;

namespace AnalyStock;

/// <summary>
///     Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : NavigationWindow
{
    public MainWindow()
    {
        InitializeComponent();
        IniApplicationEvent();
    }

    private void IniApplicationEvent()
    {
        Closing += NavigationWindow_Closing;
        //Closed += (s, e) => Application.Current.Shutdown();
        Application.Current.DispatcherUnhandledException += App_DispatcherUnhandledException;
        AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
        TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;
    }

    private void NavigationWindow_Closing(object sender, CancelEventArgs e)
    {
        if ("是否退出系统?".IsConfirmMessage())
        {
            if (IsBusyApplicationWorking())
            {
                "系统数据处理工作没有完成...".NotifyMessage();
                e.Cancel = true;
            }

            return;
        }

        e.Cancel = true;
    }

    private bool IsBusyApplicationWorking()
    {
        return ApplicationParam.IsBusyOfBackgroundWorking;
    }

    /// 系统异常处理

    #region

    //主线程未处理异常
    private void App_DispatcherUnhandledException
        (object sender, DispatcherUnhandledExceptionEventArgs e)
    {
        e.Exception.Message.ErrorMessage();
        e.Handled = true;
    }

    //未处理线程异常(如果主线程未处理异常已经处理，该异常不会触发)
    private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
    {
        if (e.ExceptionObject is Exception ex)
        {
            ex.Message.ErrorMessage();
        }
    }

    //未处理的Task内异常
    private void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
    {
        e.Exception.Message.ErrorMessage();
    }

    //保存、显示异常信息
    private void ProcessException(Exception exception)
    {
        //保存日志
        //提醒用户
    }

    #endregion
}